package com.hushan.standby.compoment;

import cn.hutool.core.thread.ThreadUtil;
import redis.clients.jedis.Jedis;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.hushan.standby.App.LOCAL_HOST;
import static com.hushan.standby.App.SOURCE_HOST;

public class RedisReplicaControl {
    // 连接到 Redis 服务器 (假设是作为从节点连接)
    private static int localPort = 6379;
    private static String localPwd = "123456";
    private static String masterPasswd = "123456";
    private static int masterPort = 6379;
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void startSlave() {
        try (Jedis jedis = new Jedis(LOCAL_HOST, localPort)) {
            jedis.auth(localPwd);
            // 获取当前 Redis 实例的角色信息
            java.util.List<Object> role = jedis.role();
            String currentRole = role.get(0).toString().toLowerCase();

            if (currentRole.equalsIgnoreCase("master")) {
                executeSQLStatements();
            }
        }
    }

    private static void executeSQLStatements() {
        try (Jedis jedis = new Jedis(LOCAL_HOST, localPort)) {
            jedis.auth(localPwd);

            // 将当前从节点变回主节点
            String responseNoOne = jedis.replicaofNoOne();
            System.out.println("Set slaveof no one command response: " + responseNoOne);

            // 设置主节点 (使当前 Redis 实例成为从节点)
            // 参数1: 主节点的 IP 地址
            // 参数2: 主节点的端口号
            jedis.configSet("masterauth", masterPasswd);
            jedis.configSet("slave-read-only", "no");
            String response = jedis.replicaof(SOURCE_HOST, masterPort);
            System.out.println("Set slaveof command response: " + response);

            // 获取当前 Redis 实例的角色信息 (master 或 slave)
            java.util.List<Object> role = jedis.role();
            System.out.println("Current Redis role: " + role.get(0));
            if (role.get(0).toString().equalsIgnoreCase("slave")) {
                System.out.println("Master IP: " + role.get(1));
                System.out.println("Master Port: " + role.get(2));
            }

            // 获取复制相关的信息
            String replicationInfo = jedis.info("replication");
            System.out.println("\nReplication Info:\n" + replicationInfo);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void startMonitoring() {
        if (scheduler.isShutdown() || scheduler.isTerminated()) {
            scheduler = Executors.newScheduledThreadPool(1);
        }
        scheduler.scheduleAtFixedRate(RedisReplicaControl::checkReplicationStatus, 0, 5, TimeUnit.SECONDS); // 每5秒监控一次，可根据需要调整间隔时间
    }

    private static void checkReplicationStatus() {
        try (Jedis jedis = new Jedis(LOCAL_HOST, localPort)) {
            if (localPwd != null && !localPwd.isEmpty()) {
                jedis.auth(localPwd);
            }

            String replicationInfo = jedis.info("replication");
            System.out.println("\n=== Redis Replication Status ===");
            System.out.println(replicationInfo);

            // 你可以进一步解析 replicationInfo 来提取关键指标并进行判断
            // 例如：
            String role = parseReplicationInfo(replicationInfo, "role");
            String connectedSlavesStr = parseReplicationInfo(replicationInfo, "connected_slaves");
            String masterLinkStatus = parseReplicationInfo(replicationInfo, "master_link_status");
            String slaveReplOffset = parseReplicationInfo(replicationInfo, "slave_repl_offset");
            String masterReplOffset = parseReplicationInfo(replicationInfo, "master_repl_offset");

            System.out.println("Role: " + role);
            if (role.equalsIgnoreCase("master")) {
                System.out.println("Connected Slaves: " + connectedSlavesStr + "\n");
            } else if (role.equalsIgnoreCase("slave")) {
                System.out.println("Master Link Status: " + masterLinkStatus);
                System.out.println("Slave Replication Offset: " + slaveReplOffset);
                System.out.println("Master Replication Offset: " + masterReplOffset);

                if (masterLinkStatus != null && masterLinkStatus.equalsIgnoreCase("up") &&
                        slaveReplOffset != null && masterReplOffset != null &&
                        slaveReplOffset.equals(masterReplOffset)) {
                    System.out.println("Slave is fully synchronized with the master." + "\n");
                } else if (masterLinkStatus != null && masterLinkStatus.equalsIgnoreCase("down")) {
                    System.err.println("Slave is disconnected from the master!");
                } else if (slaveReplOffset != null && masterReplOffset != null &&
                        Long.parseLong(masterReplOffset) - Long.parseLong(slaveReplOffset) > 100) {
                    System.out.println("Slave is lagging behind the master." + "\n");
                }
            }
        }
    }

    private static String parseReplicationInfo(String info, String key) {
        String[] lines = info.split("\n");
        for (String line : lines) {
            if (line.startsWith(key + ":")) {
                return line.substring(key.length() + 1).trim();
            }
        }
        return null;
    }

    // 程序结束时关闭调度器
    public static void stopSlave() {
        try (Jedis jedis = new Jedis(LOCAL_HOST, localPort)) {
            jedis.auth(localPwd);

            // 获取当前 Redis 实例的角色信息
            java.util.List<Object> role = jedis.role();
            String currentRole = role.get(0).toString().toLowerCase();

            if (currentRole.equalsIgnoreCase("slave")) {
                // 将当前从节点变回主节点
                String responseNoOne = jedis.replicaofNoOne();
                System.out.println("Set slaveof no one command response: " + responseNoOne);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void startNotify() {
        startMonitoring();
    }
}
